<template>
  <div style="width: 100%">
    <el-input style="display:none" v-model="ctCodeString"></el-input>
    <el-input :readonly="inputReadonly || disabled" class="mis-input" v-model="ctNameString" v-if="!multiple"
      @focus="handleFocus" @blur="handleBlur"></el-input>
    <el-input :readonly="true" type="textarea" autosize class="mis-input" v-model="ctNameString"
      v-if="multiple"></el-input>
    <el-button :disabled="disabled" class="mis-button" icon="el-icon-more" @click="handleClick"></el-button>
    <el-dialog :visible.sync="openTreeTransfer" v-if="openTreeTransfer" :title="dialogTitle" width="800" @close="cancel()"
      append-to-body>
      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="multiple ? 12 : 24">
          <div class="head-container">
            <el-input v-model="userName" :placeholder="searchPlaceholder" clearable size="small"
              prefix-icon="el-icon-search" @keyup.enter.native="searchUserName"
              style="margin-bottom: 20px;width:calc(100% - 120px)" />
            <el-button type="primary" @click="searchUserName" style="margin: 0 0 20px 10px;width:100px;"
              size="small">搜索</el-button>
          </div>
          <div class="head-container mis-tree-transfer">
            <el-tree :data="treeDataOptions" node-key="ctLevelC" :empty-text="emptyText" :props="defaultProps" ref="tree"
              :filter-node-method="filterNode" :style="{ height: 'calc(100vh - 460px)', overflow: 'auto' }"
              @[event]="handleNodeClick" :expand-on-click-node="!multiple" :show-checkbox="multiple"
              :highlight-current="!multiple" :default-checked-keys="defalutValue" :check-on-click-node="!multiple"
              :accordion="true" :default-expanded-keys="defaultExpandKeys" :render-content="misRenderContent"
              :disable-branch-nodes="true" />
            <!-- <el-tree
              :data="treeDataOptions"
              node-key="ctLevelC"
              empty-text="人员为空"
              :props="defaultProps"
              ref="tree"
              :filter-node-method="filterNode"
              :style="{height:'calc(100vh - 360px)',overflow:'auto'}"

              @[event]="handleNodeClick"
              :expand-on-click-node="!multiple"
              :show-checkbox="multiple"
              :highlight-current="!multiple"
              :default-checked-keys="defalutValue"
              :check-on-click-node="!multiple"
              :accordion="true"
              :current-node-key="defalutValue[0]"
            />-->
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="12" v-if="multiple">
          <div class="tree-ul-container" :style="{ height: 'calc(100vh - 408px)', overflow: 'auto' }">
            <ul class="tree-ul">
              <li v-for="(item) in filterList" v-bind:key="item.ctLevelC"
                @dblclick="() => setChecked(item.ctLevelC, false)" class="tree-li">{{ item.ctName }}</li>
            </ul>
          </div>
        </el-col>
      </el-row>
      <div slot="footer">
        <el-button type="default" @click="clearAndClose">置空</el-button>
        <el-button type="default" @click="cancel">关闭</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import request from '@/utils/request'
import store from '@/store/index'
import { getFunNo } from '@/utils/party'
import { misRenderContent } from '@/utils'
export default {
  name: 'MisTreeTransfer',
  props: {
    emptyText: {
      type: String,
      default: '人员为空',
    },
    // 搜索框的placeholder
    searchPlaceholder: {
      type: String,
      default: '请输入人员姓名',
    },
    // dialog窗体的title
    dialogTitle: {
      type: String,
      default: '选择人员',
    },
    // 是否多选
    selectMultiple: {
      type: Boolean,
      default: false,
    },

    //最大选择数
    max: {
      type: [Number],
      default: 0,
    },
    //树类型
    misTreeType: {
      type: [Number, String],
      default: 101,
    },
    //父传Code
    setValueCode: {
      type: [Number, String],
      default: '',
    },
    //父传Name
    setValueName: {
      type: [Number, String],
      default: '',
    },
    inputReadonly: {
      type: Boolean,
      default: true,
    },
    // 是否根节点可选
    disableBranchNodes: {
      type: Boolean,
      default: false,
    },
    //是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      defaultExpandKeys: [],
      store: store,
      //未转换的树
      initTreeData: [],
      //绑定树的具体数据
      treeDataOptions: [],
      //选择值
      selectedTree: [],
      //默认值
      defalutValue: [],
      //右侧列表值
      selectList: [],
      ctName: [],
      ctNameString: '',
      ctCode: [],
      ctCodeString: '',
      ctLevelP: '',
      ctLevelPName: '',
      openTreeTransfer: false,
      defaultProps: {
        children: 'children',
        label: (data, node) => {
          if (data.ctCodeP == '0' && this.misTreeType == 103) {
            return data.ctName + '(' + data.ctCode + ')'
          } else {
            return data.ctName
          }
        },
        // 'ctName',
        // disabled:function(data,node){
        //   if(node && node.ctCodeP=="2"){
        //     return true
        //   }
        // }
      },
      //多人根节点
      // RootNode: {
      //   ctCode: '',
      //   ctCodeP: '2',
      //   ctLevelC: 'group',
      //   ctLevelP: '',
      //   ctName: '我的群组',
      // },
      //人员名称
      userName: undefined,
      //树双击事件
      treeClickCount: 0,
      timer: 0,
      //是否多选
      multiple: false,

      event: 'check',
      // 遮罩层
      loading: [],
      //树loading
      treeLoading: false,
      focus: false,
    }
  },
  computed: {
    filterList() {
      let filter = this.filterSelect(this.selectList, ['ctCode'])
      return filter
    },
  },
  watch: {
    // userName(val) {
    //   this.$refs.tree.filter(val)
    // },
    ctNameString(val) {
      if (this.focus) {
        this.ctNameString = val.replace('|', '')
        this.$emit('updateTreeTransferVal', val + '|' + this.ctCodeString)
      }
    },
    ctCodeString(val) { },
    setValueName(val) {
      this.ctNameString = val
    },
    setValueCode(val) {
      this.ctCodeString = val
      this.defalutValue = val ? val.split(',') : []
    },
  },
  created() {
    if (this.max == 1) {
      this.multiple = true
      this.event = 'check'
    } else {

      this.multiple = false
      this.event = 'check-change'
    }
    this.refresh()
  },

  mounted() { },
  methods: {
    misRenderContent,
    searchUserName() {
      this.$refs.tree.filter(this.userName)
    },
    addAttr(data) {
      return data.forEach((item) => {
        if (item.ctCodeP == '2') {
          item.disabled = true
        } else {
          item.disabled = false
        }
      })
    },
    filterSelect(arr = [], keys = []) {
      const keySets = new Map(keys.map((k) => [k, new Set()]))
      return arr.filter((x) => {
        const exist = keys.some((k) => keySets.get(k).has(x[k]))
        if (!exist) {
          keys.forEach((k) => keySets.get(k).add(x[k]))
        }
        return !exist
      })
    },
    handleFocus(val) {
      this.focus = true
    },
    handleBlur(val) {
      this.focus = false
    },
    refresh() {
      this.ctNameString = this.setValueName
      this.ctCodeString = this.setValueCode
      this.defalutValue = this.setValueCode ? this.setValueCode.split(',') : []
    },
    // 提取树数据
    getTreeValue() {
      return request({
        method: 'get',
        url: 'spspublic/treeview/' + this.misTreeType,
      })
    },
    // getGroupTreeValue() {
    //   return request({
    //     method: 'get',
    //     url: 'spspublic/treeview/104',
    //   })
    // },
    handleClick() {
      this.handleLoading()
      this.openTreeTransfer = true
      this.refresh()
      // this.multiple ? this.getGroupTreeselect() : this.getTreeselect()
      this.getTreeselect()
    },
    //查询部门下拉树结构不带群组
    getTreeselect() {
      this.getTreeValue()
        .then((response) => {
          // let sortData=this.handleSortData(response.data)
          this.initTreeData = response.data

          this.treeDataOptions = this.handleTree(
            this.initTreeData,
            'ctLevelC',
            'ctLevelP'
          )
          this.defaultExpandKeys = [this.treeDataOptions[0].ctLevelC]
          // this.$nextTick(() => {
          //   // 默认高亮选中节点
          //   if (this.multiple) {

          this.selectList = this.$refs.tree.getCheckedNodes(true)
          //   }
          // })
          this.loading.close()
        })
        .catch((error) => {
          this.loading.close()
        })
    },
    // getGroupTreeselect() {
    //   this.getTreeValue()
    //     .then((response) => {
    //       // let sortData=this.handleSortData(response.data)
    //       this.initTreeData = response.data
    //       this.getGroupTreeValue()
    //         .then((response2) => {
    //           if (response2.data) {
    //             this.initTreeData.push(this.RootNode)
    //           }
    //           // let sortData2=this.handleSortData(response2.data)
    //           this.initTreeData.push(...response2.data)
    //           this.addAttr(this.initTreeData)
    //           this.treeDataOptions = this.handleTree(
    //             this.initTreeData,
    //             'ctLevelC',
    //             'ctLevelP'
    //           )
    //           this.defaultExpandKeys = [this.treeDataOptions[0].ctLevelC]
    //           this.$nextTick(() => {
    //             // 默认高亮选中节点
    //             if (this.multiple) {
    //               this.selectList = this.$refs.tree.getCheckedNodes(true)
    //             }
    //           })
    //           this.loading.close()
    //         })
    //         .catch((error) => {
    //           this.loading.close()
    //         })
    //     })
    //     .catch((error) => {
    //       this.loading.close()
    //     })
    // },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.ctName.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data, checkbox, node) {
      // //debugger
      if (this.multiple) {
        this.MultipleCheckedNodes()
      } else {
        if (data.ctCodeP == '1') {
          return
        }
        this.treeClickCount++
        //单次点击次数超过2次不作处理,直接返回,也可以拓展成多击事件
        if (this.treeClickCount >= 2) {
          return
        }
        //计时器,计算300毫秒为单位,可自行修改
        this.timer = window.setTimeout(() => {
          if (this.treeClickCount == 1) {
            //把次数归零
            this.treeClickCount = 0
            //单击事件处理
          } else if (this.treeClickCount > 1) {
            //把次数归零
            this.treeClickCount = 0
            //双击事件
            this.SingleCheckedNodes(checkbox)
          }
        }, 300)
      }
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.ctCode,
        label: node.ctLevelC,
        children: node.ctLevelP,
        disabled: node.ctCodeP == '2' ? true : false,
      }
    },
    MultipleCheckedNodes() {
      // //debugger
      let CheckedNodes = this.$refs.tree.getCheckedNodes(true).filter((item) => {
        return item.ctCodeP == '0'
      })
      CheckedNodes = this.filterSelect(CheckedNodes, ['ctCode'])
      this.selectList = CheckedNodes
      this.ctCode = CheckedNodes.map((item) => {
        return item.ctCode
      })
      this.ctCodeString = this.ctCode.join(',')
      this.ctName = CheckedNodes.map((item) => {
        return item.ctName
      })
      this.ctNameString = this.ctName.join(',')
    },
    SingleCheckedNodes(checkbox) {
      let CheckedNodes = this.$refs.tree.getCurrentNode()
      if (CheckedNodes.ctCodeP !== '0') {
        return
      } else {
        this.selectList[0] = CheckedNodes
        this.ctCode = CheckedNodes.ctCode
        this.ctCodeString = CheckedNodes.ctCode
        this.ctName = CheckedNodes.ctName
        this.ctNameString = CheckedNodes.ctName
        this.ctLevelP = CheckedNodes.ctLevelP
        let LevelP = this.initTreeData.filter((item) => {
          return item.ctLevelC == this.ctLevelP
        })[0]
        this.ctLevelPName = LevelP.ctName
        this.$emit(
          'updateTreeTransferVal',
          this.ctNameString +
          '|' +
          this.ctCodeString +
          '|' +
          this.ctLevelPName +
          '|' +
          this.ctLevelP
        )
        this.openTreeTransfer = false
      }
    },
    setChecked(ctLevelC, boolen) {
      this.$refs.tree.setChecked(ctLevelC, boolen)
      this.MultipleCheckedNodes()
    },
    cancel() {
      this.ctNameString = this.setValueName
      this.ctCodeString = this.setValueCode
      this.defalutValue = this.setValueCode ? this.setValueCode.split(',') : []
      this.selectList = []
      this.openTreeTransfer = false
    },
    clearAndClose() {
      this.ctNameString = ''
      this.ctCodeString = ''
      this.userName = ''
      this.defalutValue = []
      this.selectList = []
      this.$emit(
        'updateTreeTransferVal',
        this.ctNameString + '|' + this.ctCodeString
      )
      this.openTreeTransfer = false
    },
    submit() {

      if (!this.multiple) {
        let CheckedNodes = this.$refs.tree.getCurrentNode()
        ////debugger
        if (!CheckedNodes) {
          //   this.$message.error('请选择人员')
          //   return
          // }
          // if (CheckedNodes.ctCodeP !== '0') {
          //   this.$message.error('请选择人员')
          //   return
        }
        // else {
        this.selectList[0] = CheckedNodes
        this.ctCode = CheckedNodes.ctCode
        this.ctCodeString = CheckedNodes.ctCode
        this.ctName = CheckedNodes.ctName
        this.ctNameString = CheckedNodes.ctName
        this.ctLevelP = CheckedNodes.ctLevelP
        let LevelP = this.initTreeData.filter((item) => {
          return item.ctLevelC == this.ctLevelP
        })[0]
        this.ctLevelPName = LevelP.ctName
        this.$emit(
          'updateTreeTransferVal',
          this.ctNameString +
          '|' +
          this.ctCodeString +
          '|' +
          this.ctLevelPName +
          '|' +
          this.ctLevelP
        )
        // }
      } else {
        //let CheckedNodes = this.$refs.tree.getCurrentNode()
        // new Array(this.$refs.tree.getCheckedNodes())

        let CheckedNodes = this.$refs.tree.getCheckedNodes()


        //debugger

        this.selectList[0] = CheckedNodes
        // this.selectList.push(CheckedNodes)
        this.ctCode = this.selectList[0].ctCode
        this.ctCodeString = this.selectList[0].ctCode
        this.ctName = this.selectList[0].ctName

        this.ctNameString = this.selectList[0].ctName
        this.ctLevelP = this.selectList[0].ctLevelP
        let LevelP = this.initTreeData.filter((item) => {
          return item.ctLevelC == this.ctLevelP
        })[0]
        this.ctLevelPName = LevelP.ctName
        // //debugger
        this.$emit(
          'updateTreeTransferVal',
          this.ctNameString + '|' + this.ctCodeString
        )
      }

      this.openTreeTransfer = false
    },
    closeTreeTransferDialog() {
      this.openTreeTransfer = false
    },
    openTreeTransferDialog() {
      this.openTreeTransfer = true
    },
    handleLoading() {
      this.loading = this.$loading({
        lock: true,
        text: '努力加载人员数据中',
        spinner: 'el-icon-loading',
        background: 'transparent',
      })
    },
  },
}
</script>
<style scoped>
.mis-input {
  width: calc(100% - 60px);
  float: left;
}

.mis-button {
  float: right;
}

.tree-li {
  cursor: pointer;
}
</style>

